<template>
  <a-modal v-model="show" title="修改成绩" @cancel="onClose" :width="800">
    <template slot="footer">
      <a-button key="back" @click="onClose">
        取消
      </a-button>
      <a-button key="submit" type="primary" :loading="loading" @click="handleSubmit">
        修改
      </a-button>
    </template>
    <a-form :form="form" layout="vertical">
      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item label='选择学生' v-bind="formItemLayout">
            <a-select v-decorator="[
              'studentId',
              { rules: [{ required: true, message: '请输入学生!' }] }
              ]">
              <a-select-option :value="item.id" v-for="(item, index) in studentList" :key="index">{{ item.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label='选择课程' v-bind="formItemLayout">
            <a-select v-decorator="[
              'courseId',
              { rules: [{ required: true, message: '请选择课程!' }] }
              ]">
              <a-select-option :value="item.id" v-for="(item, index) in courseList" :key="index">{{ item.courseName }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label='所属学期' v-bind="formItemLayout">
            <a-input v-decorator="[
            'semester',
            { rules: [{ required: true, message: '请输入所属学期!' }] }
            ]"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label='分数'>
            <a-input-number style="width: 100%" :min="0" :max="100" :step="1" v-decorator="[
            'score',
            { rules: [{ required: true, message: '请输入分数!' }] }
            ]"/>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script>
import {mapState} from 'vuex'
function getBase64 (score) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(score)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}
const formItemLayout = {
  labelCol: { span: 24 },
  wrapperCol: { span: 24 }
}
export default {
  name: 'scoreEdit',
  props: {
    scoreEditVisiable: {
      default: false
    }
  },
  computed: {
    ...mapState({
      currentUser: state => state.account.user
    }),
    show: {
      get: function () {
        return this.scoreEditVisiable
      },
      set: function () {
      }
    }
  },
  data () {
    return {
      rowId: null,
      formItemLayout,
      form: this.$form.createForm(this),
      loading: false,
      scoreList: [],
      previewVisible: false,
      previewImage: ''
    }
  },
  mounted () {
    this.getStudentList()
    this.getCourseList()
  },
  methods: {
    getStudentList () {
      this.$get('/cos/student-info/list').then((r) => {
        this.studentList = r.data.data
      })
    },
    getCourseList () {
      this.$get('/cos/course-info/list').then((r) => {
        this.courseList = r.data.data
      })
    },
    handleCancel () {
      this.previewVisible = false
    },
    async handlePreview (score) {
      if (!score.url && !score.preview) {
        score.preview = await getBase64(score.originscoreObj)
      }
      this.previewImage = score.url || score.preview
      this.previewVisible = true
    },
    picHandleChange ({ scoreList }) {
      this.scoreList = scoreList
    },
    imagesInit (images) {
      if (images !== null && images !== '') {
        let imageList = []
        images.split(',').forEach((image, index) => {
          imageList.push({uid: index, name: image, status: 'done', url: 'http://127.0.0.1:9527/imagesWeb/' + image})
        })
        this.scoreList = imageList
      }
    },
    setFormValues ({...score}) {
      this.rowId = score.id
      let fields = ['courseId', 'studentId', 'semester', 'score']
      let obj = {}
      Object.keys(score).forEach((key) => {
        if ((key === 'courseId' || key === 'studentId') && score[key] != null) {
          score[key] = score[key].toString()
        }
        if (fields.indexOf(key) !== -1) {
          this.form.getFieldDecorator(key)
          obj[key] = score[key]
        }
      })
      this.form.setFieldsValue(obj)
    },
    reset () {
      this.loading = false
      this.form.resetFields()
    },
    onClose () {
      this.reset()
      this.$emit('close')
    },
    handleSubmit () {
      // 获取图片List
      let images = []
      this.scoreList.forEach(image => {
        if (image.response !== undefined) {
          images.push(image.response)
        } else {
          images.push(image.name)
        }
      })
      this.form.validateFields((err, values) => {
        values.id = this.rowId
        values.images = images.length > 0 ? images.join(',') : null
        if (!err) {
          this.loading = true
          this.$put('/cos/score-info', {
            ...values
          }).then((r) => {
            this.reset()
            this.$emit('success')
          }).catch(() => {
            this.loading = false
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
